<style lang="scss">
.cascader-block {
  height: 275px;
  width: 502px;
  .cascader-tab {
    width: 500px;
    .cascader-tab-item.active {
      border-color: #409eff !important;
      color: #409eff !important;
    }
  }
  .el-cascader-menu {
    width: 500px;
    //padding:15px 5px 6px;
    padding-top: 15px;
    padding-left: 5px;
    padding-right: 5px;
    .el-cascader-node {
      display: block;
      float: left;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      margin: 0 0 10px 10px;
      height: 24px;
      line-height: 22px;
      padding: 0 12px;
      font-size: 12px;
    }
    .el-cascader-menu__wrap {
      margin-bottom: 0 !important;
    }
    .el-cascader-node__postfix:before {
      content: '';
    }
    .el-cascader-node__prefix:before {
      content: '';
    }
  }
}
</style>
<template>
  <div v-if="block && !checkStrictly" class="ui-block-cascader">
    <el-cascader v-model="model" ref="cascader" :options="options" :props="initProps" :placeholder="placeholder" :show-all-levels="showAllLevels" @active-item-change="handleItemChange" @focus="handleCascaderFocus" popper-class="cascader-block" :size="size" :clearable="clearable" :collapse-tags="collapseTags"></el-cascader>
    <el-input style="visibility:hidden; position:absolute; left:9999px" v-model="modelId"></el-input>
  </div>
  <div v-else>
    <el-cascader v-model="model" ref="cascader" :options="options" :props="initProps" :placeholder="placeholder" :show-all-levels="showAllLevels" @active-item-change="handleItemChange" :size="size" :clearable="clearable" :collapse-tags="collapseTags"></el-cascader>
    <el-input style="visibility:hidden; position:absolute; left:9999px" v-model="modelId"></el-input>
  </div>
</template>
<script>
export default {
  name: 'ui-cascader',
  props: {
    checkStrictly: Boolean,
    placeholder: {
      type: String,
      default: '请选择'
    },
    value: {
      type: Array,
      required: false
    },
    showAllLevels: {
      type: Boolean,
      default: true
    },
    level: {
      type: Number,
      default: 3
    },
    modelId: String,
    modelLabel: String,
    firstLimit: {
      type: Array
    },
    block: Boolean,
    collapseTags: Boolean,
    size: String,
    props: Object,
    clearable: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      model: [],
      options: [
        { data_code: '11', data_name: '北京', children: [] },
        { data_code: '12', data_name: '天津', children: [] },
        { data_code: '13', data_name: '河北省', children: [] },
        { data_code: '14', data_name: '山西省', children: [] },
        { data_code: '15', data_name: '内蒙古自治区', children: [] },
        { data_code: '21', data_name: '辽宁省', children: [] },
        { data_code: '22', data_name: '吉林省', children: [] },
        { data_code: '23', data_name: '黑龙江省', children: [] },
        { data_code: '31', data_name: '上海', children: [] },
        { data_code: '32', data_name: '江苏省', children: [] },
        { data_code: '33', data_name: '浙江省', children: [] },
        { data_code: '34', data_name: '安徽省', children: [] },
        { data_code: '35', data_name: '福建省', children: [] },
        { data_code: '36', data_name: '江西省', children: [] },
        { data_code: '37', data_name: '山东省', children: [] },
        { data_code: '41', data_name: '河南省', children: [] },
        { data_code: '42', data_name: '湖北省', children: [] },
        { data_code: '43', data_name: '湖南省', children: [] },
        { data_code: '44', data_name: '广东省', children: [] },
        { data_code: '45', data_name: '广西壮族自治区', children: [] },
        { data_code: '46', data_name: '海南省', children: [] },
        { data_code: '50', data_name: '重庆', children: [] },
        { data_code: '51', data_name: '四川省', children: [] },
        { data_code: '52', data_name: '贵州省', children: [
          {data_code: '5224', data_name: '毕节市'}
        ] },
        { data_code: '53', data_name: '云南省', children: [] },
        { data_code: '54', data_name: '西藏自治区', children: [] },
        { data_code: '61', data_name: '陕西省', children: [] },
        { data_code: '62', data_name: '甘肃省', children: [] },
        { data_code: '63', data_name: '青海省', children: [] },
        { data_code: '64', data_name: '宁夏回族自治区', children: [] },
        { data_code: '65', data_name: '新疆维吾尔自治区', children: [] },
        { data_code: '71', data_name: '台湾', children: [] },
        { data_code: '81', data_name: '香港特别行政区', children: [] },
        { data_code: '82', data_name: '澳门特别行政区', children: [] },
        { data_code: '90', data_name: '钓鱼岛', children: [] }
      ],
      initProps: {
        value: 'data_code',
        label: 'data_name',
        children: 'children',
        checkStrictly: this.checkStrictly,
        ...this.props
      },
      tabs: [
        { index: 0, name: '省' },
        { index: 1, name: '市' },
        { index: 2, name: '县' },
        { index: 3, name: '乡' },
        { index: 4, name: '街' }
      ],
      firstClick: false
    }
  },
  mounted() {
    //第一级筛选
    if (this.firstLimit && this.firstLimit.length > 0) {
      let temporary = []
      for (let item of this.options) {
        if (jQuery.inArray(item.data_code, this.firstLimit) !== -1) {
          temporary.push(item)
        }
      }
      this.options = temporary
    }
    this.init()
  },
  watch: {
    model(newVal, oldVal) {
      if (this.props && this.props.multiple) {
        let arr = []
        newVal.forEach(item => {
          arr.push(item[item.length - 1])
        })
        this.$emit('update:modelId', arr.join(','))
      } else {
        this.$emit('update:modelId', newVal[newVal.length - 1])
      }
      setTimeout(() => {
        //新版本更新按照新属性组装数据
        if (this.props && this.props.multiple) { 
          let arr = []
          this.$refs.cascader.checkedNodes.forEach(item => {
            let labelArr = item.label.split('/')
            for (let i = 0; i < labelArr.length; i++) {
              labelArr[i] = labelArr[i].replace(/(^\s*)|(\s*$)/g, '')
            }
            arr.push(labelArr.join(''))
          })
          this.$emit('update:modelLabel', arr.join(','))
        } else {
          let labelArr = this.$refs.cascader.inputValue.split('/')
          for (let i = 0; i < labelArr.length; i++) {
            labelArr[i] = labelArr[i].replace(/(^\s*)|(\s*$)/g, '')
          }
          this.$emit('update:modelLabel', labelArr.join(''))
        }
      })
    },
    modelId(newVal, oldVal) {
      if (this.modelId) {
        if (this.model.length === 0) {
          this.init()
        }
      } else {
        this.model = []
        if (this.block) this.firstClick = false
      }
    }
  },
  methods: {
    init() {
      if (this.modelId) {
        //id切分
        let count =
          this.modelId.length > 6
            ? (this.modelId.length - 6) / 3 + 3
            : this.modelId.length / 2
        let idArray = []
        for (let i = 0, long = 0; i < count; i++) {
          long += i > 2 ? 3 : 2
          idArray.push(this.modelId.substr(0, long))
        }

        //初始化回显
        let initArray = []
        let promise = new Promise(function(resolve, reject) {
          resolve()
        })
        for (let i = 0; i < idArray.length - 1; i++) {
          promise = promise.then(data => {
            return new Promise((resolve, reject) => {
              initArray.push(idArray[i])
              let init = JSON.parse(JSON.stringify(initArray))
              this.handleItemChange(init, resolve)
            })
          })
        }
        promise.then(() => {
          this.model = idArray

          //取消初始化进来的验证
          let form = jQuery(this.$el).parents('form')
          if (form.length > 0 && form[0].__vue__) {
            this.$el.classList.add('offset-success')
            setTimeout(() => {
              form[0].__vue__.clearValidate()
              this.$el.classList.remove('offset-success')
            })
          }
        })
      }
    },
    findOption(value, options) {
      for (let key in options) {
        if (options[key].data_code === value) {
          return options[key]
        }
      }
    },
    handleItemChange(val, resolve) {
      //坨坨
      if (this.block) {
        let cascaderMenus = jQuery('.el-cascader__dropdown')
        cascaderMenus.find('.el-cascader-menu').css('display', 'none')
      }
      let activeId = val[val.length - 1]
      this.$http
        .get(`/common/data/listArea?data_code=${activeId}`)
        .then(data => {
          let activeOption = { children: this.options }
          for (let key in val) {
            activeOption = this.findOption(val[key], activeOption.children)
          }
          if (activeOption.children) {
            if (data[activeId].length > 0) {
              let activeData = data[activeId]
              if (val.length < this.level - 1) {
                for (let i in activeData) {
                  activeData[i].children = []
                }
              }
              activeOption.children = activeData
            }
          }
          //坨坨
          if (this.block) {
            let index = val.length
            let cascaderMenus = jQuery('.el-cascader__dropdown')
            if (cascaderMenus.find('.cascader-tab-item').length < +index + 1) {
              let temp = `<a class="item cascader-tab-item" index="${index}">${this.tabs[index].name}</a>`
              cascaderMenus.find('.cascader-tab-box').append(temp)
            }
            cascaderMenus.find('.cascader-tab-item').removeClass('active')
            cascaderMenus
              .find('.cascader-tab-item')
              .eq(index)
              .addClass('active')
            cascaderMenus.find('.el-cascader-menu').css('display', 'none')
            cascaderMenus
              .find('.el-cascader-menu:last-child')
              .css('display', 'block')
          }
          resolve && resolve()
        })
    },
    handleCascaderFocus() {
      if (!this.firstClick) {
        this.firstClick = true
        let tabs = JSON.parse(JSON.stringify(this.tabs))
        if (this.block) {
          if (this.modelId) {
            tabs.splice(this.level, 5 - this.level)
          } else {
            tabs.splice(1, 4)
          }
        }
        setTimeout(() => {
          jQuery('.el-cascader__dropdown .cascader-tab').remove()
          let tabDom = `
                            <div class="cascader-tab">
                                <div class="ui secondary pointing menu cascader-tab-box">
                                     ${tabs
                                       .map(
                                         tab => `
                                        <a class="item cascader-tab-item" index="${tab.index}">${tab.name}</a>
                                     `
                                       )
                                       .join('')}
                                </div>
                            </div>
                        `
          let cascaderMenus = jQuery('.el-cascader__dropdown')
          cascaderMenus.prepend(tabDom)
          //初始化
          cascaderMenus.find('.cascader-tab-item:last-child').addClass('active')
          cascaderMenus.find('.el-cascader-menu').css('display', 'none')
          cascaderMenus
            .find('.el-cascader-menu:last-child')
            .css('display', 'block')
          //操作
          cascaderMenus.on('click', '.cascader-tab-item', function() {
            $(this)
              .parent()
              .children()
              .removeClass('active')
            $(this).addClass('active')
            cascaderMenus.find('.el-cascader-menu').css('display', 'none')
            cascaderMenus
              .find('.el-cascader-menu')
              .eq($(this).attr('index'))
              .css('display', 'block')
          })
        })
      }
    }
  }
}
</script>

